package manage.action;

import m.appserver.ResponseUtil;
import m.common.action.ActionMeta;
import m.common.action.RequestMeta;
import m.common.action.VuePageResult;
import m.common.action.VueResult;
import m.common.model.util.ModelQueryList;
import m.common.model.util.QueryCondition;
import m.html.VueListResult;
import m.html.element.attr.Align;
import m.html.element.attr.ButtonType;
import m.html.list.*;
import m.system.cache.CacheUtil;
import m.system.lang.PageInfo;
import m.system.util.JSONMessage;
import m.system.util.ObjectUtil;
import m.system.util.StringUtil;
import manage.model.AdminGroup;
import manage.model.AdminGroupLink;
import manage.model.AdminLogin;
import manage.run.ModuleInitRun;
import manage.service.AdminLoginService;
import manage.service.AdminSettingService;
import manage.util.CaptchaUtil;
import manage.util.DictionaryUtil;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

@ActionMeta(name="manage/adminLogin")
public class AdminLoginAction extends StatusAction {
	
	private AdminLogin model;
	private AdminGroupLink link;
	private String imageCode;
	private String password;
	public void admin() throws UnsupportedEncodingException{
		this.getResponse().outPath(ModuleInitRun.getAdminPage());
	}
	public JSONMessage remind() {
		JSONMessage message=new JSONMessage();
		try {
			model=getSessionAdmin();
			//菜单消息
			Map<String,Object> menu= new HashMap<>();
			menu.put("A1101", "3");
			menu.put("A1102", "new");
			menu.put("Q51", "3");
			menu.put("Q5152", "hold");
			menu.put("P51", "5");
			message.push("menu", menu);
			message.push("code", 0);
		} catch (Exception e) {
			message.push("code", 1);
		}
		return message;
	}
	public JSONMessage isLogin(){
		JSONMessage message=new JSONMessage();
		message.push("codeVerify", CaptchaUtil.isMastVerify(getIpAddress()+getSessionCookie()));
		try {
			message.push("model", getSessionAdmin());
			message.push("assist",getSessionAssist());
			message.push("orgGroup",getSessionOrgGroup());
			message.push("setting",getService(AdminSettingService.class).getAllSetting(ObjectUtil.getOid(getSessionAdmin())));
			message.push("powers",getAdminOperPower());
			fillJSONResult(message,true,"");
		} catch (Exception e) {
			fillJSONResult(message,false,e);
		}
		return message;
	}
	public void getCaptchaCode() throws IOException {
		ResponseUtil response=getResponse();
		response.setHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache,must-revalidate,post-check=0,pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.outBufferedImage(CaptchaUtil.getImageCode(getIpAddress()+getSessionCookie()), "jpg");
	}
	/**
	 * 登录
	 * 
	 */
	public JSONMessage doLogin(){
		JSONMessage message=new JSONMessage();
		try {
			CaptchaUtil.verifyCaptcha(getIpAddress()+getSessionCookie(), imageCode);
			model.setPassword(StringUtil.toMD5(model.getPassword()));
			model=getService(AdminLoginService.class).loginVerification(model);
			setSessionAdmin(model);
			getService(AdminLoginService.class).updateLastInfo(model, getIpAddress());
			message.push("model", model);
			fillJSONResult(message,true,"登录成功");
			CaptchaUtil.clearMastVerify(getIpAddress()+getSessionCookie());
			CaptchaUtil.clearCode(getIpAddress()+getSessionCookie());
		} catch (Exception e) {
			CaptchaUtil.setMastVerify(getIpAddress()+getSessionCookie());
			fillJSONResult(message,false,e);
		}
		message.push("codeVerify", CaptchaUtil.isMastVerify(getIpAddress()+getSessionCookie()));
		return message;
	}
	/**
	 * 退出登录
	 * 
	 */
	public JSONMessage doLogout(){
		clearSessionAdmin();
		JSONMessage json=new JSONMessage();
		json.push("code", 0);
		return json;
	}

	/**
	 * 保存
	 * 
	 */
	public JSONMessage doSave(){
		JSONMessage result=new JSONMessage();
		try {
			verifyAdminOperPower("manage_system_power");
			String msg=getService(AdminLoginService.class).save(model,link,password);
			CacheUtil.clear(AdminLogin.class, model.getOid());
			fillJSONResult(result,true,msg);
		} catch (Exception e) {
			fillJSONResult(result,false,e);
		}
		return result;
	}
	/**
	 * 保存
	 * 
	 */
	public JSONMessage doSave4Self(){
		JSONMessage result=new JSONMessage();
		try {
			AdminLogin admin=getSessionAdmin();
			if(null==admin) throw noLoginException;
			if(null==model||!model.getUsername().equals(admin.getUsername())){
				throw noPowerException;
			}
			model.setAdminGroup(admin.getAdminGroup());
			String msg=getService(AdminLoginService.class).save(model,password);
			CacheUtil.clear(AdminLogin.class, admin.getOid());
			fillJSONResult(result,true,msg);
		} catch (Exception e) {
			fillJSONResult(result,false,e);
		}
		return result;
	}
	@RequestMeta(params = {"realname","orgGroup","roleGroup"})
	public JSONMessage getAllAdmin(String realname,String orgGroup,String roleGroup) {
		JSONMessage result=new JSONMessage();
		try {
			AdminLogin admin=getSessionAdmin();
			if(null==admin) throw noLoginException;
			verifyAdminOperPower(getStatusPower());
			PageInfo pageInfo=getService(AdminLoginService.class).getAll(this.getPage(),realname,orgGroup,roleGroup);
			result.push("list", pageInfo.getList());
			result.push("count",pageInfo.getCount());
			fillJSONResult(result,true,"");
		} catch (Exception e) {
			fillJSONResult(result,false,e);
		}
		return result;
	}
	public VueResult toEdit4Self() {
		return new VuePageResult("page/base/editMyAdminLogin.js")
			.addParam("model",getSessionAdmin());
	}
	public VueResult toEdit() throws Exception {
		verifyAdminOperPower("manage_system_power");
		if(null==model) {
			model=new AdminLogin();
		}else if(!StringUtil.isSpace(model.getOid())){
			model=ModelQueryList.getModel(model,"*","headImage.*","adminGroup.*");
		}
		if(null!=link&&null!=link.getAdminGroup()) {
			link.setAdminGroup(ModelQueryList.getModel(link.getAdminGroup(), "*","parent.*"));
		}
		return new VuePageResult("page/base/editAdminLogin.js")
			.addParam("model",model)
			.addParam("link", link);
	}
	public VueResult adminLoginList() throws Exception{
		verifyMenu("A1101","A1102");
		boolean power=hasAdminOperPower(getStatusPower());
		String adminGroupOid=getParamsValue("adminGroupOid");
		VueListResult result=getVueListResult("管理员列表",AdminLogin.class,"action/manage/adminLogin/adminLoginList");
		result.setSubTitle("添加或者编辑管理员信息。");
		result.setFunction(true,true);
		//result.setSelection("oid", false,"record.oid=='1'");
		result.addCol(toIndexColumn());
		if(power) result.addCol(toLinkColumn("用户名", "username",
			new ListEvent("page/base/viewGroupMenuPage.js", EventType.POPOVER,800)
				.addParam("adminOid","oid")
		).setSort(true));
		else result.addCol(toTextColumn("用户名", "username",true));
		result.addCol(toTextColumn("真实姓名", "realname",true));
		if(StringUtil.isSpace(adminGroupOid)) {
			result.addCol(toTextColumn("管理员组", "adminGroup.oid",true).setDictType(AdminGroup.class,"A"));
		}else {
			result.addCondition(QueryCondition.eq("adminGroup.oid", adminGroupOid));
		}
		result.addCol(toDateTimeColumn("创建时间", "createDate",160,true).setSort(true));
		result.addCol(toDateTimeColumn("最后登录时间", "lastLoginTime",160,true).setSort(true));
		result.addCol(toNumberColumn("登录次数", "loginCount").setNumberFormat("#,##0").setCount(ListCount.SUM));
		result.addCol(toStatusColumn(power));
		if(power) result.addCol(toSpaceColumn("操作",100,
			ListButton.drawer("修改", ButtonType.PRIMARY,"action/manage/adminLogin/toEdit",600, SuccessMethod.REFRESH)
				.addParam("model.oid","oid")
		).setFixed(Align.RIGHT));
		if(power) result.addButton(
			ListButton.modal("添加",ButtonType.PRIMARY,"action/manage/adminLogin/toEdit",600,SuccessMethod.REFRESH)
				.addQueryParam("model.adminGroup.oid","adminGroupOid")
		);
		return result;
	}

	@Override
	public void doRecoveryCallback() {
		DictionaryUtil.clear(AdminLogin.class);
	}

	@Override
	public void doDisableCallback() {
		DictionaryUtil.clear(AdminLogin.class);
	}

	public AdminLogin getModel() {
		return model;
	}
	public void setModel(AdminLogin model) {
		this.model = model;
	}
	@Override
	public String[] getStatusPower() {
		return new String[]{"manage_system_power"};
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getImageCode() {
		return imageCode;
	}
	public void setImageCode(String imageCode) {
		this.imageCode = imageCode;
	}
	public AdminGroupLink getLink() {
		return link;
	}
	public void setLink(AdminGroupLink link) {
		this.link = link;
	}
}
